import fetch from 'node-fetch';

export class ExamplePlugin extends plugin {
  constructor() {
    super({
      name: '查bfangled',
      dsc: 'zy-yyds',
      event: 'message',
      priority: -Infinity,
      rule: [
        {
          reg: '^#?(b站)?查房(.*)$',
          fnc: 'cf'
        }
      ]
    });
  }

  async cf(e) {
    let roomid = e.msg.replace(/#?(b站)?查房/g, "").trim();
    
    try {

      const roomInfoResponse = await fetch(`https://api.live.bilibili.com/room/v1/Room/get_info?room_id=${roomid}`);
      const roomInfoData = await roomInfoResponse.json();
      
      if (roomInfoData.code !== 0) {
        console.error('直播间信息请求失败:', roomInfoData.message || roomInfoData.msg);
        return;
      }

      const apiUrl = `https://api.live.bilibili.com/xlive/web-room/v1/dM/gethistory?roomid=${roomid}`;
      const response = await fetch(apiUrl);
      const data = await response.json();

      if (data.code === 0) { 
        const allMessages = [...(data.data.admin || []), ...(data.data.room || [])];
        
        const liveInfoTemplate = this.formatLiveInfo(roomInfoData.data, roomid);
        
        const formattedMessages = this.formatMessages(allMessages);
        
        const forwardMsgData = {
          group_id: e.group_id,
          user_id: e.user_id,
          message: [
            {
              type: 'node',
              data: {
                nickname: e.sender.nickname,
                user_id: e.user_id,
                content: [
                  {
                    type: 'markdown',
                    data: {
                      content: liveInfoTemplate
                    }
                  },
                  ...formattedMessages.map(formattedMessage => ({
                    type: 'node',
                    data: {
                      nickname: e.sender.nickname,
                      user_id: e.user_id,
                      content: [
                        {
                          type: 'markdown',
                          data: {
                            content: formattedMessage
                          }
                        }
                      ]
                    }
                  }))
                ],
                news: [{ text: "ZY - YYDS" }]
              }
            }
          ],
          news: [{ text: "ZY - YYDS" }]
        };

        await e.bot.sendApi('send_group_forward_msg', forwardMsgData);
      } else {
        console.error('弹幕信息请求失败:', data.message || data.msg);
      }
    } catch (error) {
      console.error('请求过程中出现错误:', error);
    }
  }

  formatLiveInfo(liveInfo, roomid) {
    const title = liveInfo.title || '无标题';
    const userCover = liveInfo.user_cover ? `![图片Holder #300px#150px](${liveInfo.user_cover})` : '';
    const areaName = liveInfo.area_name || '未知分区';
    const hotWords = liveInfo.hot_words ? liveInfo.hot_words.join(', ') : '无热词';
    const tags = liveInfo.tags || '无';

    return `
[***${title}***](https://live.bilibili.com/${roomid})
${userCover}
---
---
分区：${areaName}
---
#直播关键词
\`\`\`json
${hotWords}
\`\`\`
---
#标签
\`\`\`json
${tags}
\`\`\`
`;
  }

  formatMessages(messages) {
    return messages.map(message => {
      const userImageHolder = `![图片Holder #50px#50px](${message.user.base.face})`;
      const userName = message.nickname;
      const isAdmin = message.isadmin === 1 ? '（管理）' : '';
      const userMessage = message.text;
      const time = message.timeline; 

      return `${userImageHolder} ${userName}${isAdmin}\n${time}\n---\n---\n\n***${userMessage}***`;
    });
  }
}